import React from 'react';
import { View, Text,ScrollView ,StyleSheet,Image,Keyboard,DeviceEventEmitter} from 'react-native';
import moment from 'moment'
import navigationhelper from 'src/components/navigationhelper'
import {CalendarList, LocaleConfig} from 'react-native-calendars';
import NavBar from 'src/components/navBar'
import Layer from 'src/components/Layer'
import {isIPhoneX} from 'src/util'
import ScrollableTabView from 'react-native-scrollable-tab-view'
import { deviceWidth, deviceHeight } from '../../../util';
import {inject,observer} from "mobx-react/native"
import { List, InputItem, Flex } from '@ant-design/react-native';
import  CardManager from '../../../service/CardManager/index'
import DateTimePicker from "react-native-modal-datetime-picker"
import { formatDate, formatAddCardDate } from 'src/utils/DateUtils'
import Picker from 'react-native-picker'


@inject('userAuth')

@observer
export default class changeCreditCard extends React.Component {

    constructor(props) {
      super(props);
      const dict = this.props.navigation.getParam('dict')
      // console.log('dict===>',dict)
      this.state = {
        id:dict.id,
        name:dict.name,
        cardNum:dict.full_card_number,
        limitMoney:dict.quota,
        validityDate:dict.valid_date,
        repaymentDay:dict.repayment_date,
        stateDay:dict.statement_date,
        CVNStr:dict.cvv2,
        banks_id:dict.banks_id,
        isShowDatePicker: false,
        datePickerValue: new Date(),
        area: ['', ''],
    }

  }

  data = [
    ['01','02','03','04','05','06','07','08','09','10','11','12'],
    ['2019','2020','2021','2022','2023','2024','2025','2026','2027','2028','2029','2030','2031',
    '2032','2033','2034','2035','2036','2037','2038']
  ]
  handleShowYearAndMonth = () => {
    Keyboard.dismiss()
    let payload = {
      pickerConfirmBtnColor: [55, 142, 251, 1],
      pickerCancelBtnColor: [55, 142, 251, 1],
      pickerBg: [255, 255, 255, 1],
      pickerData:this.data,
      selectedValue: this.state.area,
      pickerTitleText: '选择年月',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnText: '确定',
      onPickerConfirm: data => {
        let str1 = data[0]
        let str2 = data[1]
        let str3 = str2.substring(2,4)
        let str4 =  `${str1+'/'+str3}`
        this.setState({validityDate:str4 })
      }
    }
    Picker.init(payload)
    Picker.show()
  }


  changeCreditCard =(quota,repaymentDay,stateDay,CVNStr,validPeriod,id)=>{
    if(!quota){
      return  Layer.showMsg('请输入额度')
    }
    if(!CVNStr){
      return  Layer.showMsg('请输入CVN2')
    }
    if(!validPeriod){
      return  Layer.showMsg('请输入有效期')
    }
    if(!stateDay){
      return  Layer.showMsg('请输入账单日')
    }
    if(!repaymentDay){
      return  Layer.showMsg('请输入还款日')
    }
    Layer.showLoading()
    CardManager.refreshBankcardUpdate({
      token: this.props.userAuth.token,
      valid_date:validPeriod,
      cvv2: CVNStr,
      repayment_date:repaymentDay,
      statement_date:stateDay,
      quota:quota,
    },id).then((res)=>{
      Layer.hiddenLoading()
      if(res.status == 'success'){
       Layer.showMsg('提交成功')
       if (this.props.navigation.state.params.callback) {
        this.props.navigation.state.params.callback()
       }
       DeviceEventEmitter.emit('refreshCardManager')
       navigationhelper.goBack() 
      }
      else{
        Layer.showMsg(res.message)
      }
    }).catch((res)=>{
      Layer.hiddenLoading()
      Layer.showMsg(res.message)
    }) 
  }

  handleShowDatePicker = (key)=> {

    Keyboard.dismiss()
    this.dateKey = key
    let { datePickerValue } = this.state
    // if (this.state[key]) {
    //   datePickerValue = new Date(this.state[key])
    // } else {
      datePickerValue = new Date()
    // }
    this.setState({ isShowDatePicker: true})
  }

  handleDatePicked = (date) => {
    let data = {isShowDatePicker: false }
    if (this.dateKey) {
      data[this.dateKey] = date
    }
    this.setState({ ...data })
  }

  handleHideDatePicker = () => {
    this.setState({ isShowDatePicker: false })
  }



    render(){

      const {id,cardNum,limitMoney,stateDay,repaymentDay,CVNStr,datePickerValue,banks_id,validityDate} = this.state

      return(
        <View style={{flex: 1}}>
        <NavBar 
          back={()=>{navigationhelper.goBack() }} 
          title={'更改信用卡信息'} 
          leftText={'返回'} 
        />
      <ScrollView>
     <List style={{marginTop:20}}>
     <InputItem
          style={styles.inputItem}
           editable={false}
           placeholder={cardNum}
            // clear
            // value={this.state.value}
            onChange={value => {
              this.setState({
                cardNum:value
              });
            }}
          
          >
     <Text style={styles.leftTextStyle}>信用卡号</Text>  

     </InputItem>

     <InputItem
            clear
            style={styles.inputItem}
            onChange={value => {
              this.setState({
                limitMoney:value
              });
            }}
            defaultValue={`${parseInt(limitMoney)}`}
            // extra={<Text>元</Text>}
            placeholder={'请输入额度'}
            editable={true}
          >
       <Text style={styles.leftTextStyle}>额度</Text> 
           
      </InputItem>

      <InputItem clear  onChange={value => { this.setState({ CVNStr:value});
         }} 
         style={styles.inputItem}
        //  extra={<Text>元</Text>}
            placeholder=  {"请输入CVN2"}
            editable={true}
            defaultValue={CVNStr}
          >
         <Text style={styles.leftTextStyle}>CVN2</Text> 
       
          </InputItem>

        <List>
        <InputItem 
          onChange={value => { this.setState({validityDate:value});
         }} 
           style={styles.inputItem}
            // defaultValue={validityDate}
            placeholder= {"请输入有效期"}
            editable={false}
            extra={
              <Flex onPress={()=>{

                this.handleShowYearAndMonth()
                // this.handleShowDatePicker('validityDate')
             }}>
             <Image style={{marginLeft:deviceWidth-140}} source={require('src/assets/icon_arrow_grey.png')}>
             </Image>
             </Flex>
             }
          >
          <View style={{flexDirection:'row'}}>
          <Text style={styles.leftTextStyle}>有效期</Text> 
            <Text style={{marginLeft:40,fontSize:15,color:'#2E2E2E',width:deviceWidth}}>{validityDate}</Text>
          </View>
          </InputItem>
         </List>

          <InputItem clear  onChange={value => { this.setState({stateDay:value});
         }} 
         style={styles.inputItem}
            defaultValue={`${stateDay}`}
        //  extra={<Text>元</Text>}
            placeholder="请输入账单日"
            editable={true}
          >
           <Text style={styles.leftTextStyle}>账单日</Text> 
          </InputItem>

          <InputItem clear  onChange={value => { this.setState({ repaymentDay:value});
         }} 
         style={styles.inputItem}
            defaultValue={`${repaymentDay}`}
        //  extra={<Text>元</Text>}
            placeholder="请输入还款日"
            editable={true}
          >
           <Text style={styles.leftTextStyle}>还款日</Text> 
          </InputItem>
    </List>
     <Flex 
      onPress={()=>{
        this.changeCreditCard(limitMoney,repaymentDay,stateDay,CVNStr,validityDate,id)       
      }}
     style={{borderRadius:10,backgroundColor:'#ff2121',height:50,marginTop:40, marginLeft:10, marginRight:10,justifyContent:'center',alignItems: 'center'}}>
     <Text style={{color:'#fff',fontSize:16,fontWeight:'bold',}}>确定</Text>
    </Flex>

       <DateTimePicker 
       mode={'date'}
        locale='zh-Hans'
        titleIOS={'选择时间'}
        cancelTextIOS={'取消'}
        confirmTextIOS={'确定'}
        date={datePickerValue}
        isVisible={this.state.isShowDatePicker}
          onConfirm={this.handleDatePicked}
          onCancel={this.handleHideDatePicker}
        />
    </ScrollView>
     </View>
      ) 
    }

}


const styles = StyleSheet.create({
  inputItem:{
    fontSize:15,
    marginTop:2,
    marginLeft:20
  },
  leftTextStyle: {
    color:'#2E2E2E',
    marginLeft:10
  },

})